package vikaa.ui;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import vikaa.tools.DialogService;
import vikaa.tools.HttpUtil;
import vikaa.wowo.R;

public class WowoActive extends Activity {
	private static final int GET_CODE_FAIL = 0;
	private static final int GET_CODE_SUCCESS = 1;
	private static final int ACTIVE_SUCCESS = 2;
	private static final int ACTIVE_FAIL = 3;
	private ImageView submitBtn;
	private EditText phoneEdt;
	private EditText passwordEdt;
	private long codetime = 0;
	private String uid;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.wowo_activie);
        uid = getIntent().getExtras().getString("uid");
		initview();
	}
	
	public void initview(){
		submitBtn = (ImageView)findViewById(R.id.submitBtn);
		submitBtn.setOnClickListener(new clickListener());
		phoneEdt = (EditText)findViewById(R.id.phoneEdt);
		passwordEdt = (EditText)findViewById(R.id.passwordEdt);
		if(getPhoneNum() != null){
			phoneEdt.setText(getPhoneNum());
		}
		phoneEdt.addTextChangedListener(mPhoneWatcher);
		passwordEdt.addTextChangedListener(mPwdWatcher);
		//DialogService.showProgressDialog(WowoActive.this, getString(R.string.active_phone_msg2));
	}
	private String getPhoneNum(){
		 TelephonyManager tManager = (TelephonyManager) this.getSystemService(TELEPHONY_SERVICE);
		 String number = tManager.getLine1Number();
		 if(!TextUtils.isEmpty(number)){
			 return number;
		 }
		 return null; 
	}
	public boolean isMobileNO(String mobiles){
		Pattern p = Pattern.compile("^((13[0-9])|(15[^4,\\D])|(18[0,5-9]))\\d{8}$");
		Matcher m = p.matcher(mobiles);
		return m.matches();
	}
	@Override
	protected Dialog onCreateDialog(int id) {
		// TODO Auto-generated method stub
		switch(id){
		case 1:
			final EditText input = new EditText(this);
			return new AlertDialog.Builder(this)
			.setTitle(getString(R.string.active_phone_msg3))
			.setView(input)
			.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener(){
				public void onClick(DialogInterface dialog, int which) {
					String code = input.getText().toString();
					String phone = phoneEdt.getText().toString();
					String password = passwordEdt.getText().toString();
					DialogService.showProgressDialog(WowoActive.this, getString(R.string.active_phone_msg4));
					new ActiveThread(phone, password, code).start();
				}
			})
			.setNegativeButton(R.string.cancel, null).create();
		default:
			return null;
		}
	}

	Handler mhandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch(msg.what){
			case GET_CODE_SUCCESS:
				DialogService.closeProgressDialog();
				break;
			case GET_CODE_FAIL:
				DialogService.closeProgressDialog();
				Toast.makeText(getApplicationContext(), (String)msg.obj, Toast.LENGTH_SHORT).show();
				break;
			case ACTIVE_SUCCESS:
				DialogService.closeProgressDialog();
				Intent intent = new Intent(WowoActive.this,Mywowo.class);
				intent.putExtra("uid", uid);
				startActivity(intent);
				finish();
				break;
			case ACTIVE_FAIL:
				DialogService.closeProgressDialog();
				Toast.makeText(getApplicationContext(), (String)msg.obj, Toast.LENGTH_SHORT).show();
				break;
			case 4:
				
				break;
			}
		}
		
	};
	class clickListener implements OnClickListener{
		public void onClick(View v) {
			// TODO Auto-generated method stub
			switch(v.getId()){
			case R.id.submitBtn:
				DialogService.showProgressDialog(WowoActive.this, getString(R.string.active_phone_msg2));
				DialogService.hideSoftKeypad(WowoActive.this);
				String phone = phoneEdt.getText().toString();
				String password = passwordEdt.getText().toString();
				if(phone.length() < 11 ){
					Toast.makeText(WowoActive.this,getString(R.string.active_phone_msg5), Toast.LENGTH_SHORT).show();
				}
				else {
					if(password.length() < 6){
						Toast.makeText(WowoActive.this,getString(R.string.active_phone_msg6), Toast.LENGTH_SHORT).show();
					}
					else{
						if(codetime == 0){
							DialogService.closeProgressDialog();
							showDialog(1);
							new GetCodeThread(phone).start();
						}
						else{
							if((Calendar.getInstance().getTimeInMillis()/1000)-codetime < 60){
								Toast.makeText(WowoActive.this,getString(R.string.active_phone_msg7), Toast.LENGTH_SHORT).show();
								showDialog(1);
							}
							else{
								DialogService.showProgressDialog(WowoActive.this, getString(R.string.active_phone_msg2));
								new GetCodeThread(phone).start();
								showDialog(1);
							}
						}
					}
				}
				break;
			}
		}
	}
	TextWatcher mPhoneWatcher = new TextWatcher() {
        private CharSequence temp;
        private int editStart ;
        private int editEnd ;
        public void beforeTextChanged(CharSequence s, int arg1, int arg2,
                int arg3) {
            temp = s;
        }
       
        public void onTextChanged(CharSequence s, int arg1, int arg2,
                int arg3) {
        }
       
        public void afterTextChanged(Editable s) {
            editStart = phoneEdt.getSelectionStart();
            editEnd = phoneEdt.getSelectionEnd();
            if (temp.length() > 11) {
                s.delete(editStart-1, editEnd);
                int tempSelection = editStart;
                phoneEdt.setText(s);
                phoneEdt.setSelection(tempSelection);
            }
            if(temp.length() == 11){
            	if(!isMobileNO(phoneEdt.getText().toString())){
            		Toast toast = new Toast(WowoActive.this);
                	toast = Toast.makeText(getApplicationContext(), getString(R.string.active_phone_msg5), Toast.LENGTH_SHORT);
                	toast.setGravity(Gravity.CENTER, 0, 0);
                	toast.show();
            		phoneEdt.setText("");
            	}
            }
        }
    };
    TextWatcher mPwdWatcher = new TextWatcher() {
        private CharSequence temp;
        private int editStart ;
        private int editEnd ;
        public void beforeTextChanged(CharSequence s, int arg1, int arg2,
                int arg3) {
            temp = s;
        }
        public void onTextChanged(CharSequence s, int arg1, int arg2,
                int arg3) {
        }
        public void afterTextChanged(Editable s) {
            editStart = passwordEdt.getSelectionStart();
            editEnd = passwordEdt.getSelectionEnd();
            if (temp.length() > 16) {
                s.delete(editStart-1, editEnd);
                int tempSelection = editStart;
                passwordEdt.setText(s);
                passwordEdt.setSelection(tempSelection);
            }
            if(passwordEdt.getText().toString().indexOf(" ") != -1){
            	Toast toast = new Toast(WowoActive.this);
            	toast = Toast.makeText(getApplicationContext(), getString(R.string.active_phone_msg8), Toast.LENGTH_SHORT);
            	toast.setGravity(Gravity.CENTER, 0, 0);
            	toast.show();
            	passwordEdt.setText("");
            }
        }
    };
	class GetCodeThread extends Thread{
		private String phone;
		public GetCodeThread(String phone) {
			super();
			this.phone = phone;
		}
		@Override
		public void run() {
			Map<String, String> map = new HashMap<String, String>();
			map.put("phone", phone);
			String url = HttpUtil.BASE_URL + "user/validataphone";
			try {
				JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(url, map));
				if(jsonObj.getString("result").equals("1")){
					codetime = Long.valueOf(jsonObj.getString("info"));
					Message msg = mhandler.obtainMessage(GET_CODE_SUCCESS);
					msg.obj = codetime;
					mhandler.sendMessage(msg);
				}
				else if(jsonObj.getString("result").equals("2")){
					String error = jsonObj.getJSONObject("info").getString("error");
					Message msg = mhandler.obtainMessage(GET_CODE_FAIL);
					msg.obj = error;
					mhandler.sendMessage(msg);
				}
				else{
					Message msg = mhandler.obtainMessage(GET_CODE_FAIL);
					msg.obj = jsonObj.getString("msg");
					mhandler.sendMessage(msg);
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
	class ActiveThread extends Thread{
		private String phone;
		private String password;
		private String code;
		public ActiveThread(String phone, String password, String code) {
			super();
			this.phone = phone;
			this.password = password;
			this.code = code;
		}
		@Override
		public void run() {
			Map<String, String> map = new HashMap<String, String>();
			map.put("phone", phone);
			map.put("password", password);
			map.put("code", code);
			String url = HttpUtil.BASE_URL + "user/activephone";
			try {
				JSONObject jsonObj = new JSONObject(HttpUtil.postRequest(url, map));
				if(jsonObj.getString("result").equals("1")){
					Message msg = mhandler.obtainMessage(ACTIVE_SUCCESS);
					mhandler.sendMessage(msg);
				}
				else if(jsonObj.getString("result").equals("2")){
					Message msg = mhandler.obtainMessage(ACTIVE_FAIL);
					msg.obj = jsonObj.getJSONObject("info").getString("error");
					mhandler.sendMessage(msg);
				}
				else{
					Message msg = mhandler.obtainMessage(ACTIVE_FAIL);
					msg.obj = jsonObj.getString("msg");
					mhandler.sendMessage(msg);
				}
			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}
